const { execquery } = require('../database/mysql')

const getList = (author, keyword) => {
  let sql =  `select * from blogs where 1=1 `
  if (author) {
    sql += `and author='${author}' `
  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += `order by createtime desc;`
  return execquery(sql)
}

const getDetail = (id) => {
  const sql = `select * from blogs where id=${id};`
  return execquery(sql).then(rows => {
    return rows[0]
  })
}

const newBlog = (postData = {}) => {
  const { title, content, author } = postData
  const createtime = Date.now()
  const sql = `insert into blogs (title, content, author, createtime) 
              values ('${title}', '${content}', '${author}', ${createtime});`
  return execquery(sql).then(insertData => {
    //console.log('insertData: ', insertData)
    return {
      id: insertData.insertId
    }
  })
}

const updateBlog = (id, postData = {}) => {
  const { title, content} = postData
  const sql = `update blogs set title='${title}', content='${content}' where id=${id};`
  return execquery(sql).then(updateData => {
    //console.log('updateData: ', updateData)
    if (updateData.affectedRows > 0) {
      return true
    }
    return false
  })
}

const deleteBlog = (id, author) => {
  const sql = `delete from blogs where id=${id} and author='${author}';`
  return execquery(sql).then(deleteData => {
    //console.log('deleteData: ', deleteData)
    if (deleteData.affectedRows > 0) {
      return true
    }
    return false
  })
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog
}